package com.gistmap.ntdc.mq;

import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.jms.*;

@Component
public class Producer {
	
	@Autowired
	private JmsMessagingTemplate jmsMessagingTemplate;
	
	@Autowired
	private Queue queue;
	
	public void send(String msg) {
		this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
	}

	public void delaySend(String text, String queueName, Long time) {
		//获取连接工厂
		ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
		try {
			//获取连接
			Connection connection = connectionFactory.createConnection();
			connection.start();
			//获取session
			Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			// 创建一个消息队列
			Destination destination = session.createQueue(queueName);
			MessageProducer producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			TextMessage message = session.createTextMessage(text);
			//设置延迟时间
			message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
			//发送
			producer.send(message);
			session.commit();
			producer.close();
			session.close();
			connection.close();
		} catch (Exception e) {
			e.getMessage();
		}
	}
}
